import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
import { reqLogin, reqInfo, reqLogout } from '@/api/login/login';
import _ from 'lodash' //导入loadsh插件
//引入vue-router里面配置好的路由信息
//引入常量路由|全部异步路由|任意路由
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import router from '@/router';
let findUserAsyncRoutes = (a: any, routes: any) => {
  return a.filter((item: any) => {
    if (routes.indexOf(item.name) != -1) {
      if (item.children && item.children.length > 0) {
        item.children = findUserAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',//用户信息名字
    avatar: '',//用户头像
    menuRoutes: [],//左侧菜单需要展示的数据
    buttonsList:[]
  }),

  actions: {
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password })
        console.log(result);
        this.token = result.token
        setToken(result.token);
        return 'ok'
      } catch (error) {
        return Promise.reject('失败')
      }
    },

    async getInfo() {
      try {
        let result = await reqInfo()
        console.log(result);
        this.name = result.name
        this.avatar = result.avatar
        //仓库存储当前用户按钮的权限
        this.buttonsList = result.buttons;
        console.log(this.buttonsList);   
        this.menuRoutes = staticRoutes
        let allRoutes = findUserAsyncRoutes(_.cloneDeep(allAsyncRoutes), result.routes)
        this.setRoute([...allRoutes, anyRoute])
        //左侧导航区域的菜单需要展示的数据
        console.log(...staticRoutes, ...allRoutes);     
        this.menuRoutes = [...staticRoutes, ...allRoutes]
        return 'ok'
      } catch (error) {
        return Promise.reject('失败')
      }
    },
    setRoute(addedRoute: any) {
      addedRoute.forEach((item: any) => {
        router.addRoute(item)
      })
    },
    async reset() {
      try {
        await reqLogout()
        console.log(router);
        console.log(allAsyncRoutes);
        // router.removeRoute()
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.name = ''
        this.avatar = ''
        this.resetReave()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    resetReave(){
      let allRouter = router.getRoutes()
      console.log(allRouter); 
      allRouter.forEach((item:any)=>{
        router.removeRoute(item.name)
      })
      this.setRoute(staticRoutes)
      //常量路由:动态添加上
      // staticRoutes.forEach((item: any) => {
      //   router.addRoute(item);
      // });
    }
  },
});
